package com.wuster.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuster.entity.dto.ReportPageDTO;
import com.wuster.entity.dto.UserAndClockDTO;
import com.wuster.entity.po.StudentFreeTime;
import com.wuster.entity.po.TeacherFreeTime;
import com.wuster.entity.po.User;
import com.wuster.entity.po.WeekReport;
import com.wuster.entity.vo.DakaVO;
import com.wuster.entity.vo.FreeTimesVO;
import com.wuster.entity.vo.InfoVO;
import com.wuster.entity.vo.ReportVO;
import com.wuster.mapper.DakaMapper;
import com.wuster.mapper.TeacherFreeMapper;
import com.wuster.mapper.UserMapper;
import com.wuster.mapper.WeekReportMapper;
import com.wuster.result.PageResult;
import com.wuster.service.TeacherService;
import com.wuster.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    DakaMapper dakaMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    WeekReportMapper weekReportMapper;
    @Autowired
    private TeacherFreeMapper teacherFreeMapper;

    /**
     * 打卡记录查询
     * @param name  学生姓名，可以为空
     * @param pageId
     * @param pageSize
     * @return
     */
    public PageResult getClocks(String name, Integer pageId, Integer pageSize) {
        Page<UserAndClockDTO> page = new Page<>(pageId, pageSize);

        //根据学生的姓名 判断是按姓名查询打卡记录，还是查询所有打卡记录
        if(name != null) {
            //按姓名模糊查找学生的打卡记录
            page = dakaMapper.getRecordByName(page, name);
        }
        else {
            //查询所有打卡记录
            page = dakaMapper.getRecords(page);
        }

        log.info("老师查询打卡{}", page.getRecords());

        //规范数据
        List<UserAndClockDTO> userAndClockDTOList = page.getRecords();
        List<DakaVO> dakaVOList = new ArrayList<>();

        //日期格式化
//        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        for (UserAndClockDTO userAndClockDTO : userAndClockDTOList){
            DakaVO dakaVO = new DakaVO();

            //设置打卡编号和日期
            dakaVO.setId(userAndClockDTO.getId());
            dakaVO.setDakaDate(userAndClockDTO.getDakaDate());
            //获取打卡时段
            dakaVO.setPeriod(userAndClockDTO.getStartTime() + "-" + userAndClockDTO.getEndTime());
            //获取有效时长
            dakaVO.setWorkTime(userAndClockDTO.getWorkTime());
            //设置姓名
            dakaVO.setName(userAndClockDTO.getUserName());

            dakaVOList.add(dakaVO);
        }

        return new PageResult(page.getTotal(), dakaVOList);
    }

    /**
     * 学生信息查询
     * @param name
     * @param pageId
     * @param pageSize
     * @return
     */
    public PageResult getInfo(String name, Integer pageId, Integer pageSize) {
        Page<User> page = new Page<>(pageId, pageSize);

        //根据学生的姓名 判断是按姓名查询学生信息，还是查询所有学生信息
        if("".equals(name) || name == null ) {
            //查询所有学生信息
            page = userMapper.selectPage(page, null);
            log.info("老师查询学生信息{}", page.getRecords());
        }
        else {
            //按姓名模糊查找学生的信息
            page = userMapper.getInfoByName(page, name);
        }

        //将查询到的user对象转化为InfoVO对象
        List<InfoVO> infoVOList = new ArrayList<>();
        List<User> userList = page.getRecords();
        for(User user : userList){
            InfoVO infoVO = new InfoVO();
            BeanUtils.copyProperties(user, infoVO);
            infoVOList.add(infoVO);
        }

        return new PageResult(page.getTotal(), infoVOList);
    }



    /**
     * 老师查询周报
     * @param reportPageDTO
     * @return
     */
    public PageResult getStudentReports(ReportPageDTO reportPageDTO) {
        Page<WeekReport> page = new Page<>(reportPageDTO.getPageId(), reportPageDTO.getPageSize());
        QueryWrapper<WeekReport> wrapper = new QueryWrapper<>();

        String name = reportPageDTO.getName();
        Date startDate = reportPageDTO.getStartDate();
        Date endDate = reportPageDTO.getEndDate();

        // 名字不为空，查询构造器加条件
        if (name != null)
            wrapper.like("name", name);

        //日期不为空，查询构造器加条件
        if (startDate != null)
            wrapper.ge("start_date", startDate);
        if (endDate != null)
            wrapper.le("end_date", endDate);

        wrapper.orderByDesc("id")
               .select("id",  "name", "start_date", "end_date", "content", "delay", "sentiment", "next_plan");

        //查询
        page = weekReportMapper.selectPage(page, wrapper);

        //将从数据库中查询到的对象转化为VO，返回给前端
        List<WeekReport> weekList = page.getRecords();
        List<ReportVO> reportVOList = new ArrayList<>();
        //处理日期范围字段
        for (WeekReport weekReport : weekList){
            ReportVO reportVO = new ReportVO();
            BeanUtils.copyProperties(weekReport, reportVO);
            reportVO.setPeriod(weekReport.getStartDate() + "~" + weekReport.getEndDate());
            reportVOList.add(reportVO);
        }

        return new PageResult(page.getTotal(), reportVOList);
    }



    /**
     * 教师查看空闲
     * @param weekId
     * @return
     */
    // TODO 待完成
    public List<FreeTimesVO> getFrees(Integer weekId) {
        //创建freeList，用于存储五天的FreeTimesVO
        List<FreeTimesVO> freeList = new ArrayList<>();

        //根据weekId判断，查询的是本周还是下周
        if (weekId ==0 || weekId == 1){
            // 获取一周的五个日期
            Date[] dateList = CommonUtils.getDateByWeekId(weekId);
            // 查询每天每个时间段的空闲人数
            for (int i = 0; i < 5; i++) {
                //QueryWrapper来进行条件的添加
                LambdaQueryWrapper<TeacherFreeTime> wrapper = new LambdaQueryWrapper();
                // 查看数据库中是否存在该条记录， 构造查询条件
                wrapper.eq(TeacherFreeTime::getDayDate, dateList[i].toString()).select();
                TeacherFreeTime teacherFree = teacherFreeMapper.selectOne(wrapper);

                // 如果查询为空，则将 teacherFree 初始化，防止空指针异常
                if (teacherFree == null)
                    teacherFree = new TeacherFreeTime();

                // 创建VO对象，并将PO对象转换为VO对象
                // 1.设置每个时间段的空闲
                FreeTimesVO freeTimesVO = new FreeTimesVO(teacherFree.getOne(), teacherFree.getTwo(),
                        teacherFree.getThree(), teacherFree.getFour(), teacherFree.getFive(),
                        teacherFree.getSix(), teacherFree.getSeven(), teacherFree.getEight(), teacherFree.getNine());
                // 2.设置空闲的日期
                freeTimesVO.setDateTime(dateList[i].toString());
                //3.设置索引（前端需要）
                freeTimesVO.setIndex(i+1);
                //4.设置weekId
                freeTimesVO.setWeekId(weekId);

                freeList.add(freeTimesVO);
            }
        }
        else{
            log.info("weekiD错误");
        }

        return freeList;
    }
}
